package com.cooba.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.application.MyApplication;
import com.cooba.utils.ACache;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2015/12/20.
 * 新闻详情
 */
public class NewsDetailsActivity extends AppCompatActivity {
    private WebView web;
    private String replyid;
    private WebSettings settings;
    private HttpUtils httpUtils;
    private RequestParams params;
    private final static String HEAD = "<h3 style=text-align:center></h3><head><style>img{max-width:100%%;height:auto; !important;}</style></head>";
    private ImageButton back;
    private Boolean isIncar;
    private String mac;
    private String dir_name;
    private ACache acache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);

        PushAgent.getInstance(this).onAppStart();

        back= (ImageButton) findViewById(R.id.news_image_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        web = (WebView) findViewById(R.id.web_News_Details);
        settings = web.getSettings();
        //settings.setTextSize(WebSettings.TextSize.NORMAL);
        //settings.setDefaultTextEncodingName("UTF-8");
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        //settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
   /*     settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //优先使用缓存
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);*/
        Intent intent = getIntent();
        replyid = intent.getStringExtra("newsDetialreplyid");
        dir_name=intent.getStringExtra("dirname");
        acache= ACache.get(this);
        initIncar();
        init(replyid);
    }

    private void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }

    private void init(final String replyid) {
        String urlnewsdetail;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("id", replyid);
        params.addBodyParameter("dir_name", dir_name);
        if (isIncar){
            urlnewsdetail="http://a.cooba.cc/Port/newsPortInfoDetail";
        }
        else {
            urlnewsdetail=ServerURL.httpUrl + ServerURL.newsDetail;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlnewsdetail, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "失败");
                String cacheData = acache.getAsString("news_detail_" + replyid);
                Log.d("wei", "新闻详情:" + acache.getAsString("news_detail_" + replyid));
                if (cacheData != null) {
                    JSONObject json = null;
                    try {
                        json = new JSONObject(cacheData);
                        String content = json.get("content").toString().replaceAll("\\\\", "");
                        String time = json.get("create_time").toString();
                        String create_time = Utils.subStrTime(time);
                        String author = json.get("author").toString();
                        String title = json.get("title").toString();
                        Log.d("wei", author + "," + create_time);
                        String html = "<html><head><style type=\"text/css\">img{max-width:100%;height:auto; !important;} </style></head><body style='font-size: 18px;color:#555555;text-align:justify;text-justify:inter-ideograph;line-height:1.5'><h3 style='text-align:center;color:black'>" + title + "</h3><span>" + create_time + "</span><span style='margin-left:20px;'>" + author + "</span>" + content + "</body></html>\n";
                        web.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(NewsDetailsActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", responseInfo.result);
                JSONObject json = null;
                try {
                    json = new JSONObject(responseInfo.result);
                    String content = json.get("content").toString().replaceAll("\\\\", "");
                    String time = json.get("create_time").toString();
                    String create_time = Utils.subStrTime(time);
                    String author = json.get("author").toString();
                    String title = json.get("title").toString();
                    Log.d("wei", author + "," + create_time);
                    String html = "<html><head><style type=\"text/css\">img{max-width:100%;height:auto; !important;}</style></head><body style='font-size: 18px;color:#555555;text-align:justify;text-justify:inter-ideograph;line-height:1.5'><h3 style='text-align:center;color:black'>" + title + "</h3><span>" + create_time + "</span><span style='margin-left:20px;'>" + author + "</span>" + content + "</body></html>\n";
                    web.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);

                    acache.put("news_detail_" + replyid, responseInfo.result, Constants.SAVE_TIME);//缓存5分钟
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    // 设置回退
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
            web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
